<template>
  <div class="content-main">
    <item-list
      class="sort-list"
      :idx="sort"
      :items="sortZh"
      @changeIdx="changeSort"
    ></item-list>

    <source-list
      :sources="source.abstracts"
      class="source-list"
      @fetchSourceAbstracts="fetchSourceAbstracts"
    ></source-list>
  </div>
</template>

<script lang="ts" setup>
import ItemList from '@/components/utils/ItemList.vue'
import SourceList from '@/components/SourceList.vue'
import { reactive, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { post } from '@/utils/request'
import { show } from '@/utils/popup'

const sortZh = ['推荐', '最热', '最新']
let sourceRestrictionAbstractsMap = reactive(new Map())

const route = useRoute()
let sort = computed(() => {
  return parseInt(route.query.s as string) || 0
})
let type = computed(() => {
  let types = ['all', '数理', '语言', '开发', '算法', '其他']
  let idx = parseInt(route.query.t as string) || 0
  return types[idx]
})
let sourceRestriction = computed(() => {
  let obj = {
    sort: sort.value,
  } as any
  if (type.value !== 'all') obj.type = type
  return obj
})

let source = computed(() => {
  let map = sourceRestrictionAbstractsMap
  if (!map.has(JSON.stringify(sourceRestriction.value)))
    map.set(JSON.stringify(sourceRestriction.value), {
      page: 0,
      abstracts: [],
    })
  let item = map.get(JSON.stringify(sourceRestriction.value))
  return item
})

watch(sourceRestriction, () => {
  fetchSourceAbstracts()
})

const router = useRouter()
function changeSort(sort: number) {
  router.push({
    path: route.path,
    query: {
      ...route.query,
      s: sort,
    },
  })
}

function fetchSourceAbstracts() {
  let restriction = sourceRestriction.value
  let item = source.value
  post('source', {
    page: ++item.page,
    ...restriction,
  })
    .then((res) => {
      if ((res.data as any).length)
        item.abstracts = item.abstracts.concat(res.data)
      else item.page--
    })
    .catch((error) => {
      show('获取文章失败')
      item.page--
    })
}
</script>

<style lang="scss" scoped>
$w: var(--innerWidthPart1);

.content-main {
  width: $w;
  background-color: white;

  .sort-list {
    --itemListWidth: calc($w * 0.6);
    --itemListHeight: 50px;
  }

  .source-list {
    --sourceListWidth: $w;
  }
}
</style>
